package com.yeyks.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yeyks.account.dal.domain.AccountInfo;
import com.yeyks.annotation.NeedToken;
import com.yeyks.annotation.SystemLog;
import com.yeyks.base.BaseController;
import com.yeyks.common.ajax.AjaxResponseBody;
import com.yeyks.common.base.Arguments;
import com.yeyks.common.base.PageInfo;
import com.yeyks.common.constants.AccountType;
import com.yeyks.common.constants.SysLogMsg;
import com.yeyks.common.exception.ServiceException;
import com.yeyks.common.param.DownloadUserByParam;
import com.yeyks.common.result.UserStatisticalResult;
import com.yeyks.common.result.user.UserDetailResult;
import com.yeyks.common.result.user.UserInfoByParamResult;
import com.yeyks.common.result.user.UserInfoByParentIdResult;
import com.yeyks.common.utils.excel.ExcelUtil;
import com.yeyks.commonReference.service.account.AccountInfoService;
import com.yeyks.consumer.dal.domain.UserInfo;
import com.yeyks.consumer.dal.domain.UserInviteRelation;
import com.yeyks.consumer.dto.UserInfoResult;
import com.yeyks.consumer.param.UserInfo.UserInfoQueryByParentIdParam;
import com.yeyks.consumer.param.UserInfo.UserInfoQueryParam;
import com.yeyks.consumer.param.UserInfo.UserInfoSetBusinessParam;
import com.yeyks.consumer.service.UserInfoService;
import com.yeyks.consumer.service.UserInviteRelationService;
import com.yeyks.web.AccountUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户管理模块
 */
@Api(tags = "用户管理")
@Slf4j
@RestController
@RequestMapping(value = "/admin/user")
public class UserController extends BaseController {

    @Autowired
    AccountInfoService accountService;

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    UserInviteRelationService userInviteRelationService;

    @NeedToken
    @ApiOperation(value = "分页查询用户列表", notes = "根据参数查询C端用户")
    @PostMapping(value = {"/query/list"})
    public ResponseEntity<?> userList(UserInfoQueryParam userInfoQueryParam,
                                      @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        if (userInfoQueryParam == null) {
            throw new ServiceException("查询参数为空");
        }
        //AccountInfo operatorInfo = accountService.token2AccountInfo(userInfoQueryParam.getToken());
        //count和list
        PageInfo pageInfo = PageInfo.of(pageNum, pageSize);
        userInfoQueryParam.setOffset(pageInfo.getOffset());
        userInfoQueryParam.setLimit(pageInfo.getLimit());

        Map<String, Object> map = new HashMap<String, Object>();
        List<UserInfoResult> userInfoList = userInfoService.queryPageList(userInfoQueryParam);
        int count = userInfoService.queryListCount(userInfoQueryParam);
        map.put("list", userInfoList);
        map.put("count", count);
        return ResponseEntity.ok(AjaxResponseBody.success(map));
    }

    /**
     * 统计一周内新增用户数
     *
     * @return
     */
    @NeedToken
    @ApiOperation(value = "统计一周内新增用户数", notes = "token通过header传入", response = UserStatisticalResult.class)
    @RequestMapping(value = "/stat/day", method = RequestMethod.POST)
    public AjaxResponseBody<List<UserStatisticalResult>> statDay() {
        AccountInfo loginUser = AccountUtils.getLoginUser();
        if (AccountType.HotelManager == loginUser.getType()) {
            throw new ServiceException("您无权查看");
        }
        //查询过去7天新增用户数
        List<UserStatisticalResult> statisticalResults = userInfoService.statDay(6);
        return AjaxResponseBody.success(statisticalResults);
    }

    @NeedToken
    @ApiOperation(value = "查询邀请用户列表（3.7.1）")
    @PostMapping("/query/by/parentid")
    public ResponseEntity<?> queryAccountByParentIdPage(@Validated UserInfoQueryByParentIdParam parentIdParam) {

        AjaxResponseBody body = AjaxResponseBody.failed();
        AccountInfo loginUser = AccountUtils.getLoginUser();
        List<UserInfo> userInfoList = userInfoService.queryUserByParentIdPage(parentIdParam);
        Integer count = userInfoService.queryUserByParentIdCount(parentIdParam);
        Map<String, Object> map = Maps.newHashMap();
        map.put("list", userInfoList);
        map.put("count", count);
        body = AjaxResponseBody.success(map);
        return ResponseEntity.ok(body);
    }


    @NeedToken
    @CrossOrigin
    @ApiOperation(value = "导出邀请用户", notes = "导出邀请用户接口")
    @PostMapping(value = "/downUserInfo/by/parentId")
    public void downMemberCardGift(@Validated UserInfoQueryByParentIdParam parentIdParam, HttpServletResponse response) {

        AccountInfo loginUser = AccountUtils.getLoginUser();
        List<UserInviteRelation> list = userInviteRelationService.list(new QueryWrapper<UserInviteRelation>().eq(UserInviteRelation.PARENT_ID, parentIdParam.getParentId()));
        List<Integer> userIds = null;
        if (!CollectionUtils.isEmpty(list)) {
            userIds = list.stream().map(UserInviteRelation::getUserId).collect(Collectors.toList());
        }
        QueryWrapper<UserInfo> query = new QueryWrapper<UserInfo>();
        if (Arguments.strNotNull(parentIdParam.getPhone())) {
            query.like(UserInfo.PHONE, parentIdParam.getPhone());
        }
        if (!CollectionUtils.isEmpty(userIds)) {
            query.in(UserInfo.ID, userIds);
        }
        List<UserInfo> userInfoList = userInfoService.list(query);
        List<UserInfoByParentIdResult> results = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(userInfoList)) {
            userInfoList.forEach(userInfo -> {
                UserInfoByParentIdResult result = new UserInfoByParentIdResult();
                result.setId(userInfo.getId());
                result.setPhone(userInfo.getPhone());
                result.setGmtCreate(userInfo.getGmtCreate());
                results.add(result);
            });
            ExcelUtil.disposeWriteExcelWithSheets(response, results, new UserInfoByParentIdResult());
        }
    }

    @SystemLog(value = SysLogMsg.USER_DISABLE)
    @NeedToken
    @ApiOperation(value = "禁用APP用户", notes = "禁用APP用户")
    @PostMapping(value = "/disable")
    public ResponseEntity<?> disable(@RequestParam(value = "userId") Integer userId) {

        AjaxResponseBody body = AjaxResponseBody.failed();
        AccountInfo loginUser = AccountUtils.getLoginUser();
        if (loginUser.getType() != AccountType.Administrator) {
            throw new ServiceException("没有操作权限");
        }

        boolean flag = userInfoService.updateById(new UserInfo().setId(userId)
                .setStatus(0));
        if (flag) {
            body = AjaxResponseBody.success("禁用成功！");
        }
        return ResponseEntity.ok(body);
    }

    @SystemLog(value = SysLogMsg.USER_ENABLE)
    @NeedToken
    @ApiOperation(value = "启用APP用户", notes = "启用APP用户")
    @PostMapping(value = "/enable")
    public ResponseEntity<?> enable(@RequestParam(value = "userId") Integer userId) {

        AjaxResponseBody body = AjaxResponseBody.failed();
        AccountInfo loginUser = AccountUtils.getLoginUser();
        if (loginUser.getType() != AccountType.Administrator) {
            throw new ServiceException("没有操作权限");
        }

        boolean flag = userInfoService.updateById(new UserInfo().setId(userId)
                .setStatus(1));
        if (flag) {
            body = AjaxResponseBody.success("启用成功！");
        }
        return ResponseEntity.ok(body);
    }

    @SystemLog(value = SysLogMsg.SET_USER_TYPE_BUSINESS)
    @NeedToken
    @ApiOperation(value = "v3.8.1设置为企业用户", notes = "v3.8.1设置为企业用户")
    @PostMapping(value = "/set/business")
    public ResponseEntity<?> setBusiness(@Valid UserInfoSetBusinessParam param) {

        AccountInfo loginUser = AccountUtils.getLoginUser();
        AjaxResponseBody body = AjaxResponseBody.failed();
        if (loginUser.getType() != AccountType.Administrator) {
            throw new ServiceException("没有操作权限");
        }
        if (param.getType() != 1 && param.getType() != 2) {
            throw new ServiceException("用户类型传输错误");
        }
        UserInfo byId = userInfoService.getById(param.getUserId());
        if (null != byId) {
            if (byId.getType() == 2) {
                throw new ServiceException("企业用户不能降级");
            }
        }
        boolean flag = userInfoService.updateById(new UserInfo().setId(param.getUserId())
                .setType(param.getType()));
        if (flag) {
            body = AjaxResponseBody.success("设置企业用户成功！");
        }
        return ResponseEntity.ok(body);
    }

    @ApiOperation(value = "v4.3.0 --> 用户详情", response = UserDetailResult.class)
    @RequestMapping(value = "/user/detail", method = RequestMethod.POST)
    public AjaxResponseBody<UserDetailResult> userDetail(Integer userId) {
        return AjaxResponseBody.success(userInfoService.userDetail(userId));
    }


    @CrossOrigin
    @ApiOperation(value = "V4.0.0 --> 导出筛选用户", notes = "导出筛选用户接口")
    @PostMapping(value = "/download/user")
    public void downloadUser(@Validated DownloadUserByParam param, HttpServletResponse response) {

        List<UserInfoResult> userInfoList = userInfoService.queryDownloadUserByParam(param);
        List<UserInfoByParamResult> results = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(userInfoList)) {
            userInfoList.forEach(userInfo -> {
                UserInfoByParamResult result = new UserInfoByParamResult();
                result.setId(userInfo.getId());
                result.setPhone(userInfo.getPhone());
                result.setGmtCreate(userInfo.getGmtCreate());
                if(userInfo.getType() == 1){
                    result.setType("否");
                }else{
                    result.setType("是");
                }
                result.setInviteCount(userInfo.getInviteCount());
                results.add(result);
            });
            ExcelUtil.disposeWriteExcelWithSheets(response, results, new UserInfoByParamResult());
        }
    }


}
